/**
 * 播放器
 * @type {Element}
 */
let playerMain = document.querySelector(".playerMain");
let recordPlayer = document.querySelector(".recordPlayer");
let musicPlayerListOuter = document.querySelector(".musicPlayerListOuter");
let songCover = document.querySelector("#songCover");
let needle = document.querySelector("#needle");
let musicPlayerBackgroundImg = document.querySelector(".musicPlayerBackgroundImg");
//  歌词
let lyrics = document.querySelector("#lyrics");

let musicPlayerSongInfo = document.querySelector(".musicPlayerSongInfo");

/**
 * 播放列表
 * @type {Element}
 */
//  播放列表
let musicPlayerListTitle = document.querySelector("#playListCount")
//  播放列表内容
let musicPlayerList = document.querySelector(".musicPlayerList")

//  歌曲操作栏
let audioPlayerList = document.querySelector("#audioPlayerList");
let audioPaste = document.querySelector("#audioPaste");
let audioPrev = document.querySelector("#audioPrev");
let audioNext = document.querySelector("#audioNext");

//  mini播放器
let miniPlayer = document.querySelector(".miniPlayer");
let miniPlayerBackgroundImage = document.querySelector("#miniPlayerBackgroundImage");
let miniPlayerLeft = document.querySelector("#miniPlayerLeft");
let miniPlayerPrev = document.querySelector("#miniPlayerPrev");
let miniPlayerNext = document.querySelector("#miniPlayerNext");
let audioControlMini = document.querySelector("#audioControlMini");

//  音乐播放器
let musicPlayerSetting = document.querySelector("#musicPlayerSetting");

/**
 * 进度条
 * @type {Element}
 */
let processBarStart = document.querySelector("#processBarStart");
let processBarEnd = document.querySelector("#processBarEnd");
let processBarPosition = document.querySelector("#processBarPosition");
let afterProcess = document.querySelector("#afterProcess");

//  获取到的音乐数据
let musicPlayData = [];
// 播放器的列表索引
let musicPlayIndex = 0;
//  是否正在展示播放列表
let isDisplayPlayList = true;
//  是否正在播放
let isPlaying = true;
//  用户是否拖动
let isUserDragging = false;
//  歌词是否显示
let isLyricsShowing = false;
//  是否正在触碰歌词
let isTouchingLyrics = false;
//  lyric计时器
let lyricIndexTimer;
+((w) => {
    w.utils.musicPlayerLoader = (songIdList, currentSongId) => {
        //  拉取当前歌单音乐信息
        getMusicFromRequest(songIdList);
        //  播放菜单
        playerListActivate();
        //  播放与暂停按钮
        playOrPause(isPlaying);
        //  初始化标题封面、歌曲信息
        initializeData(currentSongId)
        draggingProcessInitialize();
        audioHook();
        audioControl();

        lyricsInitialize(currentSongId);
        lyricsSetting();
        stopScroll();

        processBar();

        function lyricsSetting() {
            playerMain.addEventListener("click", evt => {
                if (!isLyricsShowing) {
                    utils.fade(recordPlayer, false);
                    utils.fade(needle, false);
                    utils.fade(lyrics, true);
                } else {
                    utils.fade(recordPlayer, true);
                    utils.fade(needle, true);
                    utils.fade(lyrics, false);
                }
                isLyricsShowing = !isLyricsShowing;
                //  获取新歌词
                lyricsInitialize(musicPlayData[musicPlayIndex].musicId);
            })
        }

        /**
         * 发送歌单请求和处理歌曲信息
         * @param songIdList
         * @returns {Promise<void>}
         */
        async function getMusicFromRequest (songIdList) {
            let ids = "";
            //  将数组分割， 每十个一组发出请求
            for (let i = 0; i < songIdList.length; i++) {
                const element = songIdList[i];
                if (i < songIdList.length - 1) {
                    ids += `${element},`;
                } else {
                    ids += `${element}`;
                }
            }
            //  获取歌曲标题等信息
            let musicInfo = await utils.request("get", `/song/detail?ids=${ids}`)
            if (musicInfo.code === 200) {
                musicInfo = musicInfo.songs;
                for (let i = 0; i < musicInfo.length; i++) {
                    let musicName = musicInfo[i].name;
                    let musicAuthor = musicInfo[i].ar[0].name;
                    let musicCover = musicInfo[i].al.picUrl;
                    let musicId = musicInfo[i].id;

                    //  获取歌曲播放地址
                    let musicPlayerInfo = await utils.request(
                        "get",
                        `/song/url?id=${songIdList[i]}`
                    );
                    if (musicPlayerInfo.code == 200) {
                        musicPlayerSrc = musicPlayerInfo.data[0].url;
                    }
                    musicPlayData.push({
                        musicName,
                        musicId,
                        musicAuthor,
                        musicCover,
                        musicPlayerSrc,
                    })
                }
            }
        }

        /**
         * 展示歌单列表业务逻辑
         */
        function playerListActivate() {
            audioPlayerList.addEventListener("click", (e) => {
                if (isDisplayPlayList) {
                    musicPlayerListOuter.style.opacity = 1;
                    musicPlayerListOuter.style.bottom = "2rem";
                }
                //   状态取反
                isDisplayPlayList = !isDisplayPlayList;
                //   将播放歌曲数据添加到播放例表中
                musicPlayerList.innerHTML = "";
                musicPlayData.forEach((element) => {
                    musicPlayerList.innerHTML += `
                    <li>
                        <div id="songName">
                            ${element.musicName}
                            <p id="songAuthor">- ${element.musicAuthor}</p>
                        </div>
                    </li>`;
                    musicPlayerListTitle.innerHTML = `(${musicPlayData.length})`;
                });
            });
            //  点击其他地方收起播放列表
            playerMain.addEventListener("click", (e) => {
                musicPlayerListOuter.style.opacity = 0;
                musicPlayerListOuter.style.bottom = "-99rem";
                isDisplayPlayList = !isDisplayPlayList;
            });
        }

        /**
         * 播放与暂停按钮
         * @param isPlaying
         */
        function playOrPause(isPlaying) {
            audioPaste.addEventListener("click", evt => {
                if (!isPlaying) {
                    console.log("取消播放")
                    audioPaste.innerHTML = "&#xea81;"
                    musicPlayerSetting.play();
                    discMoving(true);
                } else {
                    console.log("继续播放")
                    audioPaste.innerHTML = "&#xea82;"
                    musicPlayerSetting.pause();
                    discMoving(false);
                }
                isPlaying = !isPlaying
            })
        }

        /**
         * 初始化歌曲信息
         * @param currentSongId
         * @returns {Promise<void>}
         */
        async function initializeData(currentSongId) {
            //  获取歌曲属信息
            let initialMusicInfo = await utils.request(
                "get",
                `/song/detail?ids=${currentSongId}`
            );
            //  获取歌曲url信息
            let musicPlayerInfo = await utils.request(
                "get",
                `/song/url?id=${currentSongId}`
            )
            if (initialMusicInfo.code === 200 && musicPlayerInfo.code === 200) {
                let musicName = initialMusicInfo.songs[0].name;
                let musicAuthor = initialMusicInfo.songs[0].ar[0].name;
                let musicCover = initialMusicInfo.songs[0].al.picUrl;
                let musicPlayerSrc = musicPlayerInfo.data[0].url;
                modifyPlayerInfo({
                    musicName,
                    musicAuthor,
                    musicCover,
                    musicPlayerSrc,
                });
                isPlaying = true;
                discMoving(isPlaying);
                try {
                    musicPlayerSetting.play();
                } catch (err) {
                    console.log(err)
                    console.log("无播放列表")
                }
                isPlaying
                    ? (audioPaste.innerHTML = "&#xea81;")
                    : (audioPaste.innerHTML = "&#xea82;")
                musicPlayerBackgroundImg.style.backgroundImage = `url("${musicCover}")`
            }
        }

        /**
         * 控制切换上一首或下一首
         */
        function audioControl() {
            //  点击上一首歌绑定监听事件
            audioPrev.addEventListener("click", (e) => {
                discMoving(false);
                //  控制播放歌曲数组下表来切换歌曲
                if (musicPlayIndex > 0) {
                    switchMusic(--musicPlayIndex);
                } else {
                    musicPlayIndex = musicPlayData.length - 1;
                    switchMusic(musicPlayIndex);
                }
                utils.zoom(audioPrev);
            })
            //  点击下一首绑定监听事件
            audioNext.addEventListener("click", (e) => {
                discMoving(false);
                if (musicPlayIndex < musicPlayData.length - 1) {
                    switchMusic(++musicPlayIndex);
                } else {
                    musicPlayIndex = 0;
                    switchMusic(musicPlayIndex);
                }
                utils.zoom(audioNext);
            })
        }

        /**
         * 音乐播放钩子函数
         */
        function audioHook() {
            //  更新当前播放歌曲的下标
            musicPlayIndex = songIdList.indexOf(currentSongId)
            // 播放器长度发生变化时
            musicPlayerSetting.addEventListener("timeupdate", (e) => {
                //  若用户尚未拖动进度条时， 时刻更新进度条
                if (!isUserDragging) {
                    processBar();
                }
                //  当结束时自动播放下一首歌曲
                if (musicPlayerSetting.ended) {
                    //  判断歌单长度，如果歌单长度为1则单曲循环
                    if (musicPlayData.length < 2) {
                        switchMusic(musicPlayIndex);
                    } else {
                        if (musicPlayIndex < musicPlayData.length - 1) {
                            musicPlayIndex += 1;
                        } else {
                            musicPlayIndex = 0
                        }
                        switchMusic(musicPlayIndex);
                        let anchorPoints = location.hash;
                        if ("#muicPlayer" !== anchorPoints) {
                            //  TODO 迷你播放器
                            modifyMiniPlayer(musicPlayData);
                        } else {

                        }
                        console.log("播放结束")
                    }
                }
                //  每秒更新一次歌词滚动位置，用节流函数减少程序负担
                utils.throttle(modifyLyricsPosition, 500, musicPlayerSetting.currentTime);
            })
        }

        /**
         * 控制碟盘的转动
         * @param isPlayings
         */
        function discMoving(isPlayings) {
            if (isPlayings) {
                songCover.style.animationPlayState = "running";
                needle.style.transform = "rotate(0deg)";
            } else {
                songCover.style.animationPlayState = "paused";
                needle.style.transform = "rotate(-30deg)";
            }
        }

        /**
         * 获取歌词
         * @param musicId
         * @returns {Promise<void>}
         */
        async function lyricsInitialize(musicId) {
            //  获取歌曲歌词
            let musicLyric = await utils.request(
                "get",
                `/lyric?id=${musicId}`
            );
            if (musicLyric.code === 200) {
                //  源歌词
                let originalLyric = musicLyric.lrc.lyric;
                lyrics.innerHTML = "";
                //  判断是否需要歌词翻译
                if ("tlyric" in musicLyric && musicLyric.tlyric.lyric) {
                    let translatedLyric = musicLyric.tlyric.lyric;
                    let formattedMusicLyrics = utils.lyricFormat(originalLyric, translatedLyric);
                    //  插入原歌词和翻译歌词
                    formattedMusicLyrics.forEach((element) => {
                        lyrics.innerHTML += `
                        <li data-time="${element.time}" class="lyricsSingle">
                            <div class="originalLyrics">${element.lyric.originalLyric}</div>
                            <div class="translatedLyrics">${element.lyric.translatedLyric}</div>
                        </li>
                        `
                    })
                } else {
                    let formattedMusicLyrics = utils.lyricFormat(originalLyric);
                    //  插入歌词
                    formattedMusicLyrics.forEach((element) => {
                        lyrics.innerHTML += `
                        <li data-time="${element.time}" class="lyricsSingle">
                            <div class="originalLyrics">${element.lyric}</div>
                        </li>
                        `
                    })
                }
                try {
                    let li = document.querySelectorAll(".lyricsSingle");
                    li[0].style.marginTop = "20rem";
                } catch (e) {
                    console.log(e)
                }
            }
        }

        /**
         * 切换音乐 输入下标
         * @param musicIndex
         */
        function switchMusic(musicIndex) {
            setTimeout(() => {
                modifyPlayerInfo(musicPlayData[musicIndex]);
                isPlaying = true;
                isPlaying
                    ? (audioPaste.innerHTML = "&#xea81;")
                    : (audioPaste.innerHTML = "&#xea82;")
                playOrPause(isPlaying);
                discMoving(isPlaying);
                musicPlayerSetting.src = musicPlayData[musicIndex].musicPlayerSrc;
                musicPlayerSetting.play();
                //  进度条处理
                processBar();
                //  歌词处理
                lyricsSetting(musicPlayData[musicIndex].musicId);
                //  修改背景
                modifyBackgroundImage();
                afterProcess.style.width = 0 + "%";
                processBarPosition.style.left = -3 + "%";
            }, 500)
        }

        /**
         * 拖动播放器进度条事件监听
         */
        function draggingProcessInitialize() {
            let moveDistance;
            let startPosition;
            let movingPosition;
            let startPositionElement;
            processBarPosition.addEventListener("touchstart", (e) => {
                isUserDragging = true;
                processBarPosition.setAttribute("id", "processBarPositionActive");
                startPosition = e.changedTouches[0].clientX;
                startPositionElement = parseFloat(processBarPosition.style.left);
            });

            processBarPosition.addEventListener("touchmove", (e) => {
                isUserDragging = true;
                movingPosition = e.changedTouches[0].clientX;
                moveDistance =
                    startPositionElement + (movingPosition - startPosition) * 0.4;
                processBarPosition.style.left = moveDistance + "%";

                afterProcess.style.width =  moveDistance + "%";
            })

            processBarPosition.addEventListener("touchend", (e) => {
                isUserDragging = false;
                processBarPosition.setAttribute("id", "processBarPosition");
                musicPlayerSetting.currentTime =
                    musicPlayerSetting.duration * moveDistance * 0.01;
                processBarPosition.style.left = moveDistance + "%";
                afterProcess.style.width = moveDistance + "%";
            })
        }

        /**
         * 修改标题封面和播放地址
         * @param musicPlayDatum
         */
        function modifyPlayerInfo(songData) {
            musicPlayerSongInfo.innerHTML = `
            <p id="musicPlayerSongTitle">${songData.musicName}</p>
            <p id="musicPlayerSongAuthor">${songData.musicAuthor}</p>
            `
            songCover.src = songData.musicCover;
            try {
                musicPlayerSetting.src = songData.musicPlayerSrc;
            } catch (err) {
                console.log(err);
            }
        }

        /**
         * 修改播放器背景
         */
        function modifyBackgroundImage() {
            try {
                let cover = musicPlayData[musicPlayIndex].musicCover;
                musicPlayerBackgroundImg.style.backgroundImage = `url("${cover}")`;
            } catch (e) {
                console.log(e);
            }
        }

        /**
         * 传入当前时间以进行歌词滚动
         * @param currentTime
         */
        function modifyLyricsPosition(currentTime) {
            let lyricsSingle = document.querySelectorAll(".lyricsSingle");
            for (let i = 0; i < lyricsSingle.length; i++) {
                const element = lyricsSingle[i];
                //  获取歌词上的time属性
                let lyricTime = element.getAttribute("data-time");
                //  如果时间相符合，则将该条歌词设为高亮显示
                if (Math.floor(lyricTime) === Math.round(currentTime)) {
                    lyricsSingle.forEach((element) => {
                        element.setAttribute("id", "");
                    })
                    element.setAttribute("id", "lyricHighlight");
                }
                if (!isTouchingLyrics) {
                    //  跳转到
                    for (let i = 0; i < lyricsSingle.length; i++) {
                        const element = lyricsSingle[i];
                        let isHighlight = element.getAttribute("id");
                        if (isHighlight) {
                            lyrics.scrollTop = i * 50;
                        }
                    }
                }
            }
        }

        /**
         * 拽动歌词时，停止滚动
         */
        function stopScroll() {
            let timer;
            lyrics.addEventListener("touchstart", evt => {
                clearTimeout(timer);
                isTouchingLyrics = true;
            });
            lyrics.addEventListener("touchend", evt => {
                timer = setTimeout(() => {
                    isTouchingLyrics = false;
                }, 3000)
            });
        }

        /**
         * 进度条初始值与时长
         */
        function processBar() {
            //  歌曲时长
            let musicDuration = musicPlayerSetting.duration * 1000;
            let musicDurationFormatted = moment(musicDuration).format("mm:ss");
            //  当前歌曲位置
            let musicCurrentTime = musicPlayerSetting.currentTime * 1000;
            let musicCurrentTimeFormatted = moment(musicCurrentTime).format("mm:ss");
            processBarStart.innerHTML = `${musicCurrentTimeFormatted}`
            processBarEnd.innerHTML = `${musicDurationFormatted}`
            //  更新小圆点的位置
            let positionPercentage = (musicCurrentTime / musicDuration) * 100 - 3;
            processBarPosition.style.left = positionPercentage + "%";
            afterProcess.style.width = positionPercentage + "%";
        }

        let backButton = document.querySelector(".musicPlayerBackButton");

        backButton.addEventListener("click", evt => {
            history.back();
            modifyMiniPlayer(musicPlayData);
            console.log(musicPlayData)
        })

        /**
         * 修改迷你播放器的相关内容
         * @param data
         */
        function modifyMiniPlayer(data) {
            console.log(data)
            //  判断地址栏，如果是播放器页面则不显示
            window.addEventListener("hashchange", (listener)=> {
                let anchorPoints = location.hash;
                let  needChanging = [
                    //  todo more pages unchecked
                    "#musicPlaylist",
                    "#musicPlayer",
                ];
                //  修改mini播放器在底部的位置
                if (anchorPoints === "#musicPlayer") {
                    miniPlayer.style.display = "none";
                } else if (needChanging.indexOf(anchorPoints) >= 0) {
                    miniPlayer.style.bottom = "0";
                } else {
                    miniPlayer.style.bottom = "5rem";
                }
            });
            let nowElement = data[musicPlayIndex];
            console.log(nowElement);
            miniPlayer.style.display = "flex";
            miniPlayerBackgroundImage.style.backgroundImage = `url(${nowElement.musicCover})`
            // console.log(nowElement.musicCover);
            miniPlayerLeft.innerHTML = `
                <img src="${nowElement.musicCover}" alt=""/>
                <p id="miniPlayerSongName">${nowElement.musicName}</p>
                <p id="miniPlayerSongAuthor">${nowElement.musicAuthor}</p>            
            `;
            miniPlayer.addEventListener("click", (e) => {
               utils.navigateTo("#musicPlayer");
               miniPlayer.style.display = "none";
            });
        }

        miniPlayerPrev.addEventListener("click", evt => {
            if (musicPlayIndex > 0) {
                musicPlayIndex -= 1;
            } else {
                musicPlayIndex = musicPlayData.length - 1;
            }
            switchMusic(musicPlayIndex);
            modifyMiniPlayer(musicPlayData);
            //  取消冒泡
            evt.stopPropagation();
        })
        miniPlayerNext.addEventListener("click", evt => {
            if (musicPlayIndex < musicPlayData.length - 1) {
                musicPlayIndex += 1;
            } else {
                musicPlayIndex = 0;
            }
            switchMusic(musicPlayIndex);
            modifyMiniPlayer(musicPlayData);
            evt.stopPropagation();
        })
        audioControlMini.addEventListener("click", evt => {
            if (!isPlaying) {
                audioControlMini.innerHTML = "&#xea81;";
                musicPlayerSetting.play();
            } else {
                audioControlMini.innerHTML = "&#xea82;";
                musicPlayerSetting.pause();
            }
            isPlaying = !isPlaying;
            evt.stopPropagation();
        })
    }
})(window)